import Message from 'element-ui/lib/message';
import MessageBox from 'element-ui/lib/message-box';

// 默认配置
const msgOptions = { confirmButtonText: '确认', cancelButtonText: '取消', showCancelButton: true, center: true, type: 'warning' };

/**
 * 创建现在DOM元素
 * @param {Blob} data
 * @param {String} name 下载文件名称
 */
function downloadFile(data, name = '') {
  const date = new Date();
  const stamp = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}${date.getMilliseconds()}`;
  const blobUrl = URL.createObjectURL(data); // 创键临时url对象
  const filename = `${name ? name + '_' : ''}${stamp}.xlsx`;
  const downloadElem = document.createElement('a');

  downloadElem.href = blobUrl;
  downloadElem.download = filename;
  downloadElem.click();
  window.URL.revokeObjectURL(blobUrl); // 释放之前创建的URL对象
}

/**
 * 导入装饰器
 * @param {String} name 导出文件名称
 * @param {Object} content 导出时确认框内容
 * @param {Object} options 弹窗的配置
 * @returns
 */
export default function(name, content, option = {}) {
  return function(target, propertyKey, descriptor) {
    const method = descriptor.value;
    descriptor.value = function(...args) {
      const that = this._isVue ? this : target;
      const options = Object.assign(msgOptions, option);

      // 弹窗确认框
      MessageBox.confirm(content, '导出提示', options)
        .then(async () => {
          const { data, status } = await method.apply(that, args);
          if (status !== 200) return this.$message.error('导出失败');
          downloadFile(data, name);
          Message.success('导出成功');
        })
        .catch(err => (err === 'cancel' ? Message.warning('你已取消了操作！') : console.log(err)));
    };
  };
}
